<template>
  <a-modal :title="title" :width="640" :visible="visible" :confirmLoading="loading" @ok="handleSubmit()"
    @cancel="handleCancel">
    <a-spin :spinning="loading">
      <a-form-model ref="form" :model="form" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-model-item label="套餐名称" prop="title">
          <a-input v-model="form.title" size="large" />
        </a-form-model-item>
        <a-form-model-item label="备注" prop="remark">
          <a-textarea v-model="form.remark" placeholder="" :rows="4" :maxlength="255" />
        </a-form-model-item>
      </a-form-model>
    </a-spin>
  </a-modal>
</template>

<script>
import api from '@/api/tijian/compackage'
export default {
  props: {
    model: {
      type: Object,
      default: () => null
    }
  },
  watch: {

  },
  data() {
    this.formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 13 }
      }
    }
    return {
      title: '新建套餐',
      loading: false,
      visible: false,
      labelCol: { lg: { span: 5 }, sm: { span: 5 } },
      wrapperCol: { lg: { span: 19 }, sm: { span: 19 } },
      form: {
        title: null,
        remark: null,
        type: 1,
      },
      rules: {
        title: [
          { required: true, message: '套餐名称不能为空', trigger: 'blur' },
        ]
      }
    }
  },
  created() {
  },
  methods: {
    show(val = null) {
      this.visible = true

      if (val) {
        this.title = '修改套餐'
        this.form = {
          id: val.id,
          title: val.title,
          remark: val.remark,
        }
      } else {
        this.title = '新建套餐'
        this.form.title = null
        this.form.remark = null
      }
    },
    handleSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.loading = true
          if (this.form.id) {
            //  编辑
            api.update(this.form).then(res => {
              this.loading = false
              this.$message.success('修改成功');
              this.visible = false
              this.$emit('ok')
            }).catch(err => {
              console.log(err);
              this.loading = false
              this.$message.error('修改失败');
            })
          } else {
            console.log(this.form);
            
            //  添加
            api.add(this.form).then(res => {
              this.loading = false
              this.$message.success('添加成功');
              this.visible = false
              this.$emit('ok')
            }).catch(err => {
              console.log(err);
              this.loading = false
              this.$message.error('添加失败');
            })
          }

        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    handleCancel() {
      this.visible = false
    }
  }
}
</script>
